package com.yk.airline.dao.common.impl;

import com.yk.airline.dao.common.api.IComSearchDao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

/**
 * Created by JohenTeng on 2018/1/30.
 */
@Repository("comSearchDao")
public class ComSearchDaoImpl<T> implements IComSearchDao<T> {

    private SessionFactory sessionFactory;

    @Resource(name = "sessionFactory")
    public void setSessionFactory(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }

    private Class<T> entity;

    public ComSearchDaoImpl(){
        Type type = this.getClass().getGenericSuperclass();
        if(type instanceof ParameterizedType){
            Type[] types = ((ParameterizedType) type).getActualTypeArguments();
            entity = (Class<T>) types[0];
        }
    }

    @Override
    public List<T> findByParams(String hql, Map<String, Object> params) {
        List<T> list = null;
        try {
            Session session  = sessionFactory.getCurrentSession();
            Query<T> query = session.createQuery(hql);
            if(params != null ) {
                query.setProperties(params);
            }
            list = query.getResultList();
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public Object findUnique(String hql, Map<String, Object> params) {
        return sessionFactory.getCurrentSession().createQuery(hql).setProperties(params).uniqueResult();
    }

    @Override
    public int findCount(String hql, Map<String, Object> params) {
        return (int)this.findUnique(hql, params);
    }

    @Override
    public List<T> findByParamsThenPage(String hql, Map<String, Object> params,int begin ,int end) {
        List<T> list = null;
        try {
            Session session  = sessionFactory.getCurrentSession();
            Query<T> query = session.createQuery(hql);
            if(params != null ) {
                query.setProperties(params);
            }
            query.setMaxResults(end);
            query.setFirstResult(begin);
            list = query.getResultList();
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

}
